package org.libarae.server.databases;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.imageio.ImageIO;

import org.libarae.communication.common.Book;
import org.libarae.server.Server;

public class ExternalDBs {
	public String getBookImage(String isbn) {
		isbn = isbn.trim();
		File myFile = new File("images/"+isbn+".png");
		if(myFile.exists())
			return myFile.getAbsolutePath();
		try {
			String src ="http://covers.openlibrary.org/b/isbn/";
			src+=isbn;
			src+="-L.jpg?default=false";
			URL url;
			url = new URL(src);
			Image img=ImageIO.read(url);
			if(img!=null){
			    File outputfile = new File("images/"+isbn+".png");
			    ImageIO.write((BufferedImage)img, "png", outputfile);
			    return outputfile.getAbsolutePath();
			}

	
		} catch (MalformedURLException e) {
			if(Server.config.inDebugMode())//DEBUG MESSAGE
				e.printStackTrace();
		} catch (IOException e) {
			if(Server.config.inDebugMode())//DEBUG MESSAGE
				e.printStackTrace();
		}
		return "";	
	}
	

	public Book getBookInfo(String isbn, String accessKey) {
		String title = "";
		String author ="";
		String publisher ="";
		String summary ="";
		if(Server.config.inDebugMode())//DEBUG MESSAGE
			System.out.println(accessKey);
		Book b = new Book();
		try {
			URL url = new URL("http://isbndb.com/api/books.xml?access_key="+accessKey+"&results=texts,details&index1=isbn&value1="+isbn);
			if(Server.config.inDebugMode())//DEBUG MESSAGE
				System.out.println(url.toString());
			URLConnection yc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				if(inputLine.startsWith("<Title>"))
				{
						title = inputLine.substring(7, inputLine.length()-8);
				}
				else if(inputLine.startsWith("<AuthorsText>"))
				{
					author = inputLine.substring(13, inputLine.length()-14);
				}
				else if(inputLine.startsWith("<PublisherText"))
				{
					publisher = inputLine.substring(inputLine.indexOf('>')+1,inputLine.length()-16);
				}
				else if(inputLine.startsWith("<Summary>")) 
				{
					summary = inputLine.substring(9, inputLine.length()-10);
				}

			}
			b.setTitle(title);
			b.setAuthor(author);
			b.setPublisher(publisher);
			b.setSummary(summary);
			b.setISBN(isbn);
			String image = this.getBookImage(isbn);
			if(!image.equals("")) {
				BufferedImage bi = ImageIO.read(new File(image));
				b.setPicture(bi);
			}
			in.close();
			return b;
		} catch (Exception e) {
			if(Server.config.inDebugMode())//DEBUG MESSAGE
				e.printStackTrace();
		}
		return null;
	}
}
